home *** CD-ROM | disk | FTP | other *** search
- Path: rain.fr!world-net!usenet
- From: Frederic LACHASSE <lachass@worldnet.fr>
- Newsgroups: comp.lang.c++
- Subject: Re: [Q] Simple question about constructors
- Date: Mon, 04 Mar 1996 22:00:17 +0000
- Organization: World-Net information exchange, Internet provider.
- Message-ID: <VA.00000054.007dde45@fred>
- References: <4ha7d2$quc@cloner4.netcom.com>
- Reply-To: lachass@worldnet.fr
- NNTP-Posting-Host: client77.sct.fr
- X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
-
- In article <4ha7d2$quc@cloner4.netcom.com>, stefmit@ix.netcom.com wrote:
- >
- > Trying to work/learn C++ from an old book, I got to a point where my
- > understanding stops: picking a sample constructor from another much
- > newer source, I came across a syntax in the form:
- > class_name :: class_name (arguments) : data_member1 (argument1), data_member2
- > (argument2) {}
- > The portion I don't know the meaning of (though I assume is kind of
- > intialization list, that would've appeared otherwise within {}, as far as I
- > learned from my book), is the portion after ":".
- > I would kindly request some elaboration on this, especially concerning a
- > statement in the source where I found this, similar to: "this is the only way
- > the initialization can be done in some cases (!!!)". Does this mean I am not
- > always able to define a constructor the way I've learned so far (in its {}
- > body)?
-
- Good habits are to initialize objects before using them. When constructing an
- object (i.e. in a constructor), you must first initialize first every base
- class and every member data of your object. For some, a default constructor
- (that is a constructor without parameters) may be used implicitely, so you
- don't need to do anything. Others may not be so lucky and you must then call
- explicitely one constructor with parameters. Such is the case for const member
- data and references. Finally, it may be more efficient for other objects to
- initialize them with a full constructor than calling first the default one then
- assigning value to the object.
-
- Examples of code:
-
- class int_vector
- {
- const int size;
- int *values;
- public:
- int_vector(int s);
- };
-
- int_vector::int_vector(int s)
- : size(s) // initialization list: size can only be initialized here
- // because it's a const int
- {
- values = new int[s]; // this could be done in the init list too
- // with "values(new int[s])" but it's not mandatory
- }
-
- // now a 3D points
- class 3Dpoint : public int_vector
- {
- public:
- 3Dpoint() : int_vector(3) {} // here the base class (int_vector) has no
- // default constructor, so we need to call one
- // explicitely
- }
-
- This syntax is only necessary (and only allowed) in constructors.
- I hope this'll help.
-
- Frederic LACHASSE (ECP 86)
- CompuServe: 100530,2005
- Internet: lachass@worldnet.fr
-
-